package com.kelai.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.kelai.common.constants.DeviceStatusEnum;
import lombok.*;

import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
import java.util.Set;

/**
 * 客户实体
 * Created by Silence on 2016/11/19.
 */
@Entity
@Table(name = "T_CUSTOMER", schema = AbstractEntity.DB_SCHEMA)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonIgnoreProperties({"organization", "parent", "children", "devices", "group", "accounts","markets"})
public class CustomerEntity extends AbstractEntity {

    /**
     * 类型：客户/目录(1客户2目录3店铺)，联系人，电话，手机，电邮，地址，
     * 国家，省份，城市，方向，经度，纬度,
     * 行业, 来源：自身/渠道, 营业开始时间，营业结束时间 时区,
     * 层级(2客户 3目录 4店铺),LOGO图片链接，是否关注，门店类型
     */
    String category = "1", contactPerson, telephone, mobile, email, address,
            country = "CN", province, city, district, latitude, longitude,
            industry, source, openTime, closeTime, extendClass , timeZone ,
            level = "2" , logoUrl , followed , shopType, store;


    /**
     * 开店日期，关店日期,保修截止日期
     */
    Date openDate,closeDate,guaranteeDeadLine;
    /**
     * 初始化状态(默认为0：未初始化，1：已初始化)
     */
    Integer initFlag;

    /**
     * 所属组织
     */
    OrganizationEntity organization;

    @OneToOne
    @JoinColumn(name = "PARENT_ID", referencedColumnName = "PK_ID")
    CustomerEntity parent;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    Set<CustomerEntity> children;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum asc")
    Set<DeviceEntity> devices;

    @ManyToOne(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    @JoinTable(name = "R_GRP_CUS", joinColumns = @JoinColumn(name = "CUS_ID", referencedColumnName = "PK_ID"),
            inverseJoinColumns = @JoinColumn(name = "GRP_ID", referencedColumnName = "PK_ID"))
    CustomerGroupEntity group;

    @ManyToMany(mappedBy = "customers", fetch = FetchType.LAZY)
    Set<MarketActivityEntity> markets;


    @OneToMany(mappedBy = "customer", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum asc")
    Set<AccountEntity> accounts;

    public String getType() {
        String type = "folder";
        if (this.getCategory() != null && this.getCategory().equals("3")){
            type = "leaf";
        }
//        if (this.getLevel() != null && this.getLevel().equals("4")){
//            type = "folder";
//        }
        return type;
    }

    public String getShopPath() {
        CustomerEntity cb = this.getParent();
        if (cb == null)
            return "";
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (cb != null) {
            sb.insert(0, "/" + cb.getName());
            cb = cb.getParent();
            if (i > 9) {
                break;
            }
            i++;
        }
        return sb.toString();
    }

    public Integer getDeviceSize() {
//        return this.getDevices() != null ? this.devices.size() : 0;
        return 0;
    }

    public Integer[] findDeviceSize() {
        Integer[] arr = new Integer[]{0, 0};
        if (this.getDevices() != null)
            this.getDevices().forEach(a -> {
                if (a.getStatus() != DeviceStatusEnum.ENABLE.getValue()){
                    arr[1] += 1;
                }
                arr[0] += 1;
            });
        return arr;
    }

    public void findDeepChildren(Set<CustomerEntity> set) {
        if (this.getCategory().equals("3")) {
            set.add(this);
            return;
        }
        if (this.getChildren() != null) {
            this.getChildren().forEach(a -> {
                if (a.getCategory().equals("3"))
                    set.add(a);
                a.findDeepChildren(set);
            });
        }
    }

    public String getParentId(){
        if(this.getParent()!=null)
            return this.getParent().getId();
        return null;
    }

    public String getParentName(){
        if(this.getParent()!=null)
            return this.getParent().getName();
        return null;
    }

    public String getTopCustomerId() {
        CustomerEntity p = this.getParent();
        int i = 0;
        while (p != null) {
            if (Objects.equals(p.getCategory(), "1"))
                break;
            p = p.getParent();
            if (i > 9) {
                break;
            }
            i++;
        }
        if (p != null)
            return p.getId();
        return this.getId();
    }

    public String getTopCustomerName() {
        CustomerEntity p = this.getParent();
        int i = 0;
        while (p != null) {
            if (Objects.equals(p.getCategory(), "1"))
                break;
            p = p.getParent();
            if (i > 9) {
                break;
            }
            i++;
        }
        if (p != null)
            return p.getName();
        return this.getName();
    }



}
